#include "TcpServer.h"
#include "Logger.h"

#include <functional>

static EventLoop* CheckLoopNotNull(EventLoop* loop)
{
    if(loop == nullptr){
        LOG_FATAL("%s:%s:%d MainLoop is nullptr", __FILE__, __FUNCTION__, __LINE__);
    }
    return loop;
}

/*
    TcpService构造流程
        1.创建一个Acceptor对象，该对象会把listenfd封装成一个channel，
            然后把这个channel对象传递给Poller[acceptChannel_.enableReading]，然后注册回调函数
        2.执行回调，并且acceptor返回一个connfd
*/
TcpServer::TcpServer(EventLoop *loop,
                const InetAddress &listenAddr,
                const std::string &nameArg,
                Option option)
            : loop_(CheckLoopNotNull(loop))
            , ipPort_(listenAddr.toIpPort())
            , name_(nameArg)
            , acceptor_(new Acceptor(loop, listenAddr, option = kReusePort))
            , threadPool_(new EventLoopThreadPool(loop, name_))
            , connectionCallback_()
            , nextConnId_(1)
{
    //当有新用户连接时，会执行TcpServer::newConnection回调
    acceptor_->setNewConnectionCallbacl(std::bind(&TcpServer::newConnection, this,
        std::placeholders::_1, std::placeholders::_2));
}

//这里设置线程个数，也就是设置了subloop的个数
void TcpServer::setThreadNum(int threadNums)
{
    threadPool_->setThreadNum(threadNums);
}

//开启服务器监听，现在是在mianloop中，所以直接使用runInLoop即可。
//runInLoop中传递了listen函数[将封装的channel传递给Poller]
void TcpServer::start(){
    if(started_++ == 0)     //防止重复启动
    {
        threadPool_->start(threadInitCallback_);    //启动底层的loop线程
        loop_->runInLoop(std::bind(&Acceptor::listen, acceptor_.get()));    //启动Acceptor
    }
}  

void TcpServer::newConnection(int sockfd, const InetAddress peerAddr)
{

}